package com.example.all4.condition;

import lombok.Data;

@Data
public class Since implements ConditionChainExecutor{

    private Integer type;
    private String name;
    private SCondition sCondition ;

    private Since(Integer type, String name, SCondition sCondition){
        this.type = type;
        this.name = name;
        this.sCondition = sCondition;
    }

    public Since(Integer type){
        this(type,"",null);
    }

    public Since(Integer type,SCondition sCondition){
        this(type,"",sCondition);
    }

    private SCondition doNextFalseExecute(SCondition sCondition){
        if(sCondition != null){
            sCondition.execute();
        }
        if(!sCondition.hasNext()){
            if(sCondition.isTrue()){
                return sCondition.executeTrueEvent();
            }else if(!sCondition.isFalse()){
                return sCondition.executeFalseEvent();
            }
        }
        if(sCondition.isTrue() && sCondition.hasNext()){
            return doNextTrueExecute(sCondition.getTrueNext());
        }
        if(!sCondition.isFalse() && sCondition.hasNext()){
            return doNextFalseExecute(sCondition.getFalseNext());
        }
        return sCondition;
    }

    private SCondition doNextTrueExecute(SCondition sCondition){
        if(sCondition != null){
            sCondition.execute();
        }
        if(!sCondition.hasNext()){
            if(sCondition.isTrue()){
                return sCondition.executeTrueEvent();
            }else if(!sCondition.isFalse()){
                return sCondition.executeFalseEvent();
            }
        }
        if(sCondition.isTrue() && sCondition.hasNext()){
            return doNextTrueExecute(sCondition.getTrueNext());
        }
        if(!sCondition.isFalse() && sCondition.hasNext()){
            return doNextFalseExecute(sCondition.getFalseNext());
        }
        return sCondition;
    }


    @Override
    public SCondition executeConditionChain(){
        SCondition resultCondition = null;
        if(sCondition != null){
            if(sCondition != null){
                sCondition.execute();
            }
            if(!sCondition.hasNext()){
                if(sCondition.isTrue()){
                    return sCondition.executeTrueEvent();
                }else if(!sCondition.isFalse()){
                    return sCondition.executeFalseEvent();
                }
            }
            if(sCondition.isTrue()){
                resultCondition = doNextTrueExecute(sCondition.getTrueNext());
            }else{
                resultCondition = doNextFalseExecute(sCondition.getFalseNext());
            }
        }
        return resultCondition;
        //System.out.println(((DeaultSCondition)resultCondition).toString());
    }
}
